import XLSX from 'xlsx'
import manba from 'manba'
import * as UserAPI from '@/Api/user'
/*
 * xlsx文件转成 array
 * file为 element-ui上传文件组建返回的file对象
 *
 * */
export function xlsxToArray(file) {
    let _fileTypeArr = ['xlsx', 'xls'];
    return new Promise((reslove, reject) => {
        if (typeof file != 'object') {
            reject('传入参数有误');
            return;
        }
        if (_fileTypeArr.indexOf(file.name.substr(parseInt(file.name.lastIndexOf('.')) + 1)) < 0) {
            reject('文件类型不匹配');
            return;
        }
        if (parseFloat(file.size) > 1024 * 1024 * 3) {
            reject('文件不能大于3M');
            return;
        }
        let _fileRead = new FileReader();
        try {
            _fileRead.onload = function(ev) {
                let tableData = XLSX.read(ev.target.result, {
                    type: 'binary'
                });
                if (tableData.Sheets.hasOwnProperty(tableData.SheetNames[0])) {
                    let _data = XLSX.utils.sheet_to_json(tableData.Sheets[tableData.SheetNames[0]], {
                        header: 1,
                        raw: true
                    }); //tableData.SheetNames[0] 只读第一张表的话
                    reslove(_data);
                } else {
                    reject('excel文档中不包含sheet表格')
                }
            }
            _fileRead.readAsBinaryString(file.raw);
        } catch (e) {
            reject('文件解析失败');
        }
    })
};
export function xlsxToJson(file, tableHeader) {
    return new Promise((reslove, reject) => {
        xlsxToArray(file)
            .then(res => {
                if (res.length <= 1) {
                    reject('上传数据为空');
                    return;
                }
                let tableData = [];
                res.forEach((dataRow, index) => {
                    if (index != 0) {
                        let _obj = {};
                        let _objLength = 0;
                        tableHeader.forEach((col, index) => {
                            if (dataRow[index]) {
                                let _str = dataRow[index].toString();
                                if (_str.replace(/(^\s*)|(\s*$)/g, "")) {
                                    _obj[col] = _str.replace(/(^\s*)|(\s*$)/g, "");
                                    _objLength += 1;
                                }
                            }
                        })
                        if (_objLength > 0) {
                            tableData.push(_obj)
                        }
                    }
                })
                reslove(tableData);
            })
            .catch(error => {
                reject(error);
            })
    });
};
/*
 * json转换成xlsx文件
 *
 *  @param {*} json Object
 *  @param {*} tableHeader array 表头
 *  @param {
 *   fileName  文件名
 *   sheetName 表格名字
 *   } info Object   生成文件信息
 *
 * */
export function JsonToXlsx(json, tableHeader, info) {

    return new Promise((reslove, reject) => {
        if (dataType(json) != 'Array') {
            reject('json格式有误');
            return;
        }
        if (dataType(tableHeader) != 'Object') {
            reject('xlsx表头格式有误')
            return;
        }
        let fileInfo = Object.assign({
            fileName: 'UploadResults' + new Date().getTime(),
            sheetName: 'sheet',
        }, info);
        let newArr = [];
        let newHeader = {};
        for (let headerKey in tableHeader) {
            newHeader[tableHeader[headerKey]] = tableHeader[headerKey];
        }
        newArr.unshift(newHeader)
        json.forEach(item => {
            let obj = {};
            for (let key in item) {
                obj[tableHeader[key]] = item[key]
            }
            newArr.push(obj);
        });
        try {
            let ws = XLSX.utils.json_to_sheet(newArr, {
                skipHeader: true
            });
            let wb = XLSX.utils.book_new();
            XLSX.utils.book_append_sheet(wb, ws, fileInfo.fileName);
            XLSX.writeFile(wb, `${fileInfo.fileName}.xlsx`);
        } catch (e) {
            reject('生产XLSX文件失败')
        }
        reslove();
    })
};
export function pickerOptions() {
    return {
        shortcuts: [{
                text: '当日',
                onClick(picker) {
                    const end = new Date();
                    const start = new Date();
                    start.setTime(new Date(start.getFullYear(), start.getMonth(), start.getDate(), 0, 0, 0));
                    end.setTime(start.getTime() + 3600 * 1000 * 24 - 1000);
                    picker.$emit('pick', [start, end]);
                }
            }, {
                text: '最近7天',
                onClick(picker) {
                    picker.$emit('pick', thisWeek());
                }
            }, {
                text: '最近30天',
                onClick(picker) {
                    const end = new Date();
                    const start = new Date();
                    end.setTime(new Date(end.getFullYear(), end.getMonth(), end.getDate(), 23, 59, 59));
                    start.setTime(end.getTime() - 3600 * 1000 * 24 * 30 + 1000);
                    picker.$emit('pick', [start, end]);
                }
            }, {
                text: '最近60天',
                onClick(picker) {
                    const end = new Date();
                    const start = new Date();
                    end.setTime(new Date(end.getFullYear(), end.getMonth(), end.getDate(), 23, 59, 59));
                    start.setTime(end.getTime() - 3600 * 1000 * 24 * 60 + 1000);
                    picker.$emit('pick', [start, end]);
                }
            },
            {
                text: '最近90天',
                onClick(picker) {
                    const end = new Date();
                    const start = new Date();
                    end.setTime(new Date(end.getFullYear(), end.getMonth(), end.getDate(), 23, 59, 59));
                    start.setTime(end.getTime() - 3600 * 1000 * 24 * 90 + 1000);
                    picker.$emit('pick', [start, end]);
                }
            }
        ]
    }
};
export function thisWeek() {
    const end = new Date();
    const start = new Date();
    end.setTime(new Date(end.getFullYear(), end.getMonth(), end.getDate(), 23, 59, 59));
    start.setTime(end.getTime() - 3600 * 1000 * 24 * 7 + 1000);
    return [start, end]
}
export function dataType(data) {
    let _type = Object.prototype.toString.call(data);
    return _type.match(/[A-Z]{1}[a-z]*/)[0]
}

export function today() {
    const end = new Date();
    const start = new Date();
    end.setTime(new Date(end.getFullYear(), end.getMonth(), end.getDate(), 23, 59, 59));
    start.setTime(end.getTime() - 3600 * 1000 * 24  + 1000);
    return [start, end]
}
/*
 *
 * 只能用来清空 该函数不纯避免其他问题
 *
 * */
export function resetSearchFrom(searchForm) {
    if (!searchForm) {
        return {}
    }
    for (let key in searchForm) {
        let _type = dataType(searchForm[key]);
        if (_type == 'String' || _type == 'Number') {
            searchForm[key] = '';
        } else if (_type == 'Array') {
            searchForm[key] = [];
        } else if (_type == 'Object') {
            searchForm[key] = {};
        } else {
            searchForm[key] = {};
        }
    }
    return searchForm
};

/*
 * 格式换搜索查询参数，对于复合参数 格式为
 *      type****FH: 'phone',
 *      ****FH: '',
 *      ****处为任意合法的命名字段
 *  @param {*} searchForm Object
 *
 * */

export function searchParamsFormat(searchForm) {
    if (dataType(searchForm) != 'Object') {
        return '传入数据有误';
    }
    let params = {};
    for (let key in searchForm) {//
        if (/^(type)[A-Z|a-z]+FH$/.test(key) || /^[A-Z|a-z]+FH$/.test(key)) {
            if (key.substr(0, 4) == 'type') {
                let _value = searchForm[key.replace('type', '')];
                if (_value && dataType(_value) == 'Array') {
                  if (_value.length == 2 && (dataType(_value[0]) == 'Date' || dataType(_value[0]) == 'Number')) {
                    params[searchForm[key] + 'StartTime'] = manba(_value[0]).format('yyyy-MM-dd HH:mm:ss')
                    params[searchForm[key] + 'EndTime'] = manba(_value[1]).format('yyyy-MM-dd HH:mm:ss')
                  } else {
                    params[searchForm[key]] = _value.join('|');
                  }
                } else {
                  params[searchForm[key]] = _value;
                }
            }
        } else {
            let _type = dataType(searchForm[key]);
            if (_type == 'Array') {
                if(key == 'timeSelect') {
                  params['startTime'] = manba(searchForm[key][0]).format('yyyy-MM-dd HH:mm:ss');
                  params['endTime'] =  manba(searchForm[key][1]).format('yyyy-MM-dd HH:mm:ss');
                } else  {
                  params[key] = searchForm[key].join('|')
                }
            } else if (_type == 'Date') {
                params[key] = manba(searchForm[key].format('yyyy-MM-dd HH:mm:ss'))
            } else {
                params[key] = searchForm[key];
            }
        }
    }
    // for (let _key in params) {
    //     if (params[_key] && params[_key].length <= 0) {
    //         delete params[_key]
    //     }
    // }
    //删除为空属性
    for (let _key in params) {
        if (_key && !params[_key]) {
            delete params[_key]
        }
    }

    return params;
}
/*
 * 方便修改初始化分页信息，返回分页相关参数
 *
 * */
export function commonPagination() {
    return {
        pageSize: 50,
        pageNo: 1,
        total: 0,
        pageSizeList: [50, 100, 150, 200]
    }
}
/*
 * 查询人员列表
 *
 * */
export function queryUser(string, cb) {
    return new Promise((resolve, reject) => {
        if (string.length <= 0) {
            cb()
            reject();
            return;
        }
        UserAPI.userNickname({
                input: string
            })
            .then(res => {
                if (res.code != '0') {
                    cb()
                    reject();
                    return;
                }
                let _arr = [];
                res.data.forEach((item) => {
                    _arr.push({
                        value: item._id
                    })
                })
                cb(_arr);
                resolve();
            })
            .catch(error => {
                cb()
                reject();
            })
    })
};
export function randomTrack() {
    let _trackArr = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
    let _track = '';
    for (let i = 0; i < 2; i++) {
        _track += _trackArr[Math.floor((Math.random() * (_trackArr.length - 1)))]
    }
    _track += new Date().getTime();
    return _track;
};
export function updateFormItemCopy(formData) {
    if (dataType(formData) != 'Object') {
        return {};
    }
    let _obj = {};
    for (let key in formData) {
        _obj['src' + key.charAt(0).toUpperCase() + key.slice(1)] = formData[key]
    }
    return _obj;
}

export function isIlleagalUserName(str) {
    let reg = /^[a-zA-Z0-9\_\.]+$/;
    return reg.test(str);
};
/*
* name 获取存储在localstorage的键名
* */
export function getLocalStorageData(name) {
  if(!localStorage in window) {
    return null;
  }
  try {
    return JSON.parse(localStorage.getItem(name))
  }
  catch(error){
    return null;
  }
}

/*
 * name 设置localstorage的值名
 * value 设置存储的内容
 * */
export function setLocalStorageData(name,value) {
  if(!localStorage in window) {
    return null;
  }
  try {
    localStorage.setItem(name,JSON.stringify(value))
    return true;
  }
  catch(error){
    return null;
  }
}
/*
* 统计数据时间格式化
* */
export function countDateTimeFormat(timString) {
  if(timString) {
    return timString.toString().substr(0,19);
  } else  {
    return ''
  }
}

/*
 * 统计数据金额格式化
 * */
export function countDateMoneyFormat(string) {
  return string;
  /*if(typeof(string) == 'number') {
    return parseFloat(string).toFixed(2);
  } else  {
    return string;
  }*/
}
